package dao

import (
	"fmt"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/ordersmonthly"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 订单相关操作 -----------------------//

type OrderAutoRenewDao struct{}

func NewOrderAutoRenewDao() *OrderAutoRenewDao {
	return &OrderAutoRenewDao{}
}

// GetAutoRenewMonthlyOrderList 查询续费订单
func (d *OrderAutoRenewDao) GetAutoRenewMonthlyOrderList(param *request.AutoPayOrderListReq) *dingo.ErrorWrap {
	var (
		lst    []*request.GetAutoRenewMonthlyAwaitListReq
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	fields := `m.app_id,m.xcx_openid openid,om.id,om.member_id,om.place_id,om.amount,om.status,om.renew_status,om.pay_type,
	om.third_trade_no,om.trade_no,om.agreement_no,om.device_sn,om.place_name,m.nick_name as member_name,om.member_phone,om.message,
	DATE_FORMAT(om.pay_time, '%Y-%m-%d %T') as pay_time,DATE_FORMAT(om.renew_time, '%Y-%m-%d %T') as renew_time,DATE_FORMAT(
	om.create_time,'%Y-%m-%d %T') as create_time,DATE_FORMAT(om.update_time, '%Y-%m-%d %T') as update_time,p.place_name`
	db := global.Orm.Debug().Table("order_monthly om").Select(fields)
	db.Joins("LEFT JOIN members m ON om.member_id=m.id").Joins("LEFT JOIN places p ON om.place_id=p.id")

	if param.MemberId > 0 {
		db.Where("om.member_id = ?", param.MemberId)
	}
	if param.TradeNo != "" {
		db.Where("om.trade_no = ? or om.third_trade_no = ? ", param.TradeNo, param.TradeNo)
	}
	if param.OutTradeNo != "" {
		db.Where("om.agreement_no = ?", param.OutTradeNo)
	}
	if param.MemberName != "" {
		db.Where("m.nick_name LIKE ?", fmt.Sprint("%", param.MemberName, "%"))
	}
	if param.Status > 0 {
		db.Where("om.status=?", param.Status)
	}
	if param.RenewStatus > 0 {
		db.Where("om.renew_status=?", param.RenewStatus)
	}
	if param.StartPayTime != "" {
		db.Where("om.pay_time>=", param.StartPayTime)
	}
	if param.EndPayTime != "" {
		db.Where("om.pay_time<=", param.EndPayTime)
	}
	if param.StartRenewTime != "" {
		db.Where("om.renew_time>=", param.StartRenewTime)
	}
	if param.EndRenewTime != "" {
		db.Where("om.renew_time<=", param.EndRenewTime)
	}
	db.Order("om.id DESC").Limit(limit).Offset(offset).Find(&lst)
	db.Limit(-1).Offset(-1).Count(&count)
	return dingo.ErrorIf(db.Error, lst, count)
}

// GetAutoRenewMonthlyAwaitList 查询待续费订单
func (d *OrderAutoRenewDao) GetAutoRenewMonthlyAwaitList() *dingo.ErrorWrap {
	var dbList []*request.GetAutoRenewMonthlyAwaitListReq
	//fields := `m.app_id,m.xcx_openid openid,om.id,period_type,member_id,agreement_no,
	//DATE_FORMAT(renew_time, '%Y-%m-%d %T')renew_time`
	//db := global.Orm.Table("order_monthly om").Select(fields)
	//db.Joins("LEFT JOIN members m ON om.member_id=m.id")
	//
	//db.Where("renew_status=?", helper.TypeNumOrderMonthlyRenewStatusNormal)
	//
	//h, _ := time.ParseDuration(fmt.Sprintf("%dh", 24))
	//
	//// 扣费日期同步
	//day := time.Now().Day()
	//if day > 28 {
	//	h, _ = time.ParseDuration(fmt.Sprintf("%dh", 24*(day-28+1)))
	//} else if day == 1 {
	//	h, _ = time.ParseDuration(fmt.Sprintf("%dh", 24*5))
	//}
	//
	//t := time.Now().Add(h).Format("2006-01-02 15:04:05")
	//db.Where("renew_time<=?", t)
	//
	//db.Order("om.id").Limit(100).Find(&dbList)
	sql := `SELECT m.app_id,m.xcx_openid openid,om.id,period_type,member_id,agreement_no,DATE_FORMAT(renew_time,'%Y-%m-%d %T')
	renew_time,DATE_FORMAT(update_renew_time,'%Y-%m-%d %T')update_renew_time FROM (SELECT om1.*,DATE_FORMAT( om1.renew_time, '%e')
	daynum FROM order_monthly om1 WHERE om1.renew_time<=DATE_ADD(NOW(), INTERVAL 5 DAY) AND renew_status=1 AND status=5)om LEFT JOIN
	members m ON om.member_id=m.id WHERE om.renew_time<=IF(period_type=1,DATE_ADD(NOW(), INTERVAL 5 DAY),DATE_ADD(NOW(), INTERVAL IF
	(daynum=1,DATE_FORMAT(DATE_SUB(renew_time, INTERVAL 1 DAY),'%e')-28+2,IF(daynum>28, daynum-28+2, 2)) DAY)) 
	AND ((DATE_FORMAT(NOW(),'%e')<=28 AND period_type=2) OR period_type=1) and m.app_id = '2021003118604316'`
	db := global.Orm.Raw(sql).Find(&dbList)
	return dingo.ErrorIf(db.Error, dbList)
}

//
func (d *OrderAutoRenewDao) GetAutoRenewMonthlyAwaitListByAppId(appid string) *dingo.ErrorWrap {
	var dbList []*request.GetAutoRenewMonthlyAwaitListReq
	sql := `SELECT m.app_id,m.xcx_openid openid,om.id,period_type,member_id,agreement_no,DATE_FORMAT(renew_time,'%Y-%m-%d %T')
	renew_time,DATE_FORMAT(update_renew_time,'%Y-%m-%d %T')update_renew_time FROM order_monthly om LEFT JOIN members m ON
m.id = om.member_id WHERE m.app_id = ? and om.agreement_no != '' and om.renew_time <= DATE_ADD(NOW(), INTERVAL 5 DAY)`
	db := global.Orm.Raw(sql, appid).Find(&dbList)
	return dingo.ErrorIf(db.Error, dbList)
}

// GetAutoRenewMonthly 查询会员包月订单 有效期内
func (d *OrderAutoRenewDao) GetAutoRenewMonthly(memberId int, inDate bool) *dingo.ErrorWrap {
	dbInfo := &request.GetAutoRenewMonthlyReq{}
	db := global.Orm.Where("member_id=?", memberId)

	if inDate {
		t := time.Now().Format("2006-01-02 00:00:00")
		db.Where("renew_time>=? AND status=?", t, helper.TypeNumOrderMonthlyStatusCompletion)
	}

	db.Order("id DESC").Find(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

// GetAutoRenewMonthlyCloseCount 查询未授权数量
func (d *OrderAutoRenewDao) GetAutoRenewMonthlyCloseCount(memberId int) *dingo.ErrorWrap {
	count := int64(0)
	closeStatus := helper.TypeNumOrderMonthlyRenewStatusClose
	payCompletionStatus := helper.TypeNumOrderMonthlyStatusCompletion
	unauthorizedStatus := helper.TypeNumOrderMonthlyRenewStatusUnauthorized

	//db := global.Orm.Table("order_monthly").Where("member_id=? AND renew_status=?", memberId, closeStatus)
	//db.Or("member_id=? AND status=? AND renew_status=?", memberId, payCompletionStatus, unauthorizedStatus)
	db := global.Orm.Table("order_monthly").Where("member_id=?", memberId)
	db.Where("renew_status=? OR (status=? AND renew_status=?)", closeStatus, payCompletionStatus, unauthorizedStatus)

	db.Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

// GetAutoRenewOrderByTradeNo 查询会员续费订单
func (d *OrderAutoRenewDao) GetAutoRenewOrderByTradeNo(tradeNo string) (*request.GetAutoRenewMonthlyAwaitListReq, error) {
	dbInfo := &request.GetAutoRenewMonthlyAwaitListReq{}

	fields := `m.app_id,m.xcx_openid openid,om.id,amount,trade_no,DATE_FORMAT(renew_time, '%Y-%m-%d %T')renew_time`
	db := global.Orm.Table("order_monthly om").Select(fields)
	db.Joins("LEFT JOIN members m ON om.member_id=m.id")
	db.Where("trade_no=?", tradeNo).Find(&dbInfo)

	return dbInfo, db.Error
}

func (d *OrderAutoRenewDao) GetAutoOrderByTradeNo(tradeNo string) (*ordersmonthly.OrderMonthlyModel, error) {
	dbInfo := &ordersmonthly.OrderMonthlyModel{}
	db := global.Orm.Table("order_monthly")
	db.Where("trade_no=?", tradeNo).Find(&dbInfo)

	return dbInfo, db.Error
}

func (d *OrderAutoRenewDao) GetAutoOrderByAgreementNo(agreementNo string) (*ordersmonthly.OrderMonthlyModel, error) {
	dbInfo := &ordersmonthly.OrderMonthlyModel{}
	db := global.Orm.Table("order_monthly")
	db.Where("amount = 1")
	db.Where("agreement_no = ?", agreementNo).Find(&dbInfo)

	return dbInfo, db.Error
}

func (d *OrderAutoRenewDao) GetAutoOrderByAgreementNoOrderByCreateTime(agreementNo string) (*ordersmonthly.OrderMonthlyModel, error) {
	dbInfo := &ordersmonthly.OrderMonthlyModel{}
	sql := "select * from order_monthly where agreement_no = ? order by create_time asc limit 1"
	db := global.Orm.Raw(sql, agreementNo).Find(&dbInfo)

	return dbInfo, db.Error
}

// CreateAutoRenewMonthly 创建会员包月订单
func (d *OrderAutoRenewDao) CreateAutoRenewMonthly(params *request.AliPayUserAgreementSignRes, tradeNo string) *dingo.ErrorWrap {
	dbInfo := &ordersmonthly.OrderMonthlyRenewDB{
		OrderMonthlyDB: ordersmonthly.OrderMonthlyDB{
			MemberId:    params.UserId,
			PlaceId:     params.PlaceId,
			Amount:      int(params.Money),
			Status:      1,
			RenewStatus: 2,
			PayType:     2,
			DeviceSn:    params.DeviceSn,
			TradeNo:     tradeNo,
			PlaceName:   params.PlaceName,
			AgreementNo: params.AgreementNo,
			ProductId:   params.ProductId,
		},
		RenewTime: params.RenewTime,
	}
	if dbInfo.RenewTime == "" {
		dbInfo.RenewTime = "1970-01-01 00:00:00"
	}

	db := global.Orm.Create(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

// CreateAutoRenewMonthlyType 创建会员包月订单,指定类型
func (d *OrderAutoRenewDao) CreateAutoRenewMonthlyType(params *request.AliPayUserAgreementSignRes, tradeNo string) *dingo.ErrorWrap {
	dbInfo := &ordersmonthly.OrderMonthlyRenewTypeDB{
		OrderMonthlyDB: ordersmonthly.OrderMonthlyDB{
			MemberId:    params.UserId,
			PlaceId:     params.PlaceId,
			Amount:      int(params.Money),
			Status:      1,
			RenewStatus: 2,
			PayType:     2,
			DeviceSn:    params.DeviceSn,
			TradeNo:     tradeNo,
			PlaceName:   params.PlaceName,
			AgreementNo: params.AgreementNo,
		},
		RenewTime:  params.RenewTime,
		PeriodType: params.PeriodType,
	}
	if dbInfo.RenewTime == "" {
		dbInfo.RenewTime = "1970-01-01 00:00:00"
	}

	db := global.Orm.Create(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

// UpdateAutoRenewMonthlyByAgreementNo 会员已续费订单更新
func (d *OrderAutoRenewDao) UpdateAutoRenewMonthlyByAgreementNo(params *ordersmonthly.OrderMonthlyModel) *dingo.ErrorWrap {
	sql := `UPDATE order_monthly SET renew_status=? WHERE renew_status=? AND trade_no<>?
  	AND agreement_no=(SELECT * FROM (SELECT agreement_no FROM order_monthly WHERE trade_no=?)a)`
	db := global.Orm.Exec(sql, helper.TypeNumOrderMonthlyRenewStatusToPay,
		helper.TypeNumOrderMonthlyRenewStatusNormal, params.TradeNo, params.TradeNo)
	return dingo.ErrorIf(db.Error)
}

// UpdateAutoRenewMonthlyByAgreementClose 签约已关闭
func (d *OrderAutoRenewDao) UpdateAutoRenewMonthlyByAgreementClose(id int) *dingo.ErrorWrap {
	db := global.Orm.Table("order_monthly").Where("id=?", id)
	db.Update("renew_status", helper.TypeNumOrderMonthlyRenewStatusClose)
	return dingo.ErrorIf(db.Error)
}

// UpdateAutoRenewMonthlyPay 更新会员包月支付订单
func (d *OrderAutoRenewDao) UpdateAutoRenewMonthlyPay(params *ordersmonthly.OrderMonthlyModel) *dingo.ErrorWrap {
	dbInfo := map[string]interface{}{}
	if params.Status != 0 {
		dbInfo["status"] = params.Status
	}
	if params.RenewStatus != 0 {
		dbInfo["renew_status"] = params.RenewStatus
	}
	if params.ThirdTradeNo != "" {
		dbInfo["third_trade_no"] = params.ThirdTradeNo
	}
	if params.PayTime != "" {
		dbInfo["pay_time"] = params.PayTime
	}
	if params.RenewTime != "" {
		dbInfo["renew_time"] = params.RenewTime
	}

	db := global.Orm.Model(&params).Where("trade_no=?", params.TradeNo)

	// 订单更新限制
	if params.Status == helper.TypeNumOrderMonthlyStatusCompletion {
		db.Where("status=?", helper.TypeNumOrderMonthlyStatusWait)
	}
	db.Updates(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

// UpdateAutoRenewMonthly 更新会员包月订单
func (d *OrderAutoRenewDao) UpdateAutoRenewMonthly(params *ordersmonthly.OrderMonthlyModel) *dingo.ErrorWrap {
	dbInfo := map[string]interface{}{}
	if params.RenewStatus != 0 {
		dbInfo["renew_status"] = params.RenewStatus
	}
	if params.AgreementNo != "" {
		dbInfo["agreement_no"] = params.AgreementNo
	}
	if params.RenewTime != "" {
		dbInfo["renew_time"] = params.RenewTime
	}

	db := global.Orm.Model(&params).Where("trade_no=?", params.TradeNo).Updates(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}
